#include "webserver.h"
#include <QDebug>

WebServer::WebServer(const QString &serverName, SslMode s, QObject *parent):QWebSocketServer(serverName, s, parent)
{
    connect(this, &WebServer::newConnection, this, &WebServer::newConnected);
}


void WebServer::newConnected()
{
    socket = nextPendingConnection();
    connect(socket, &QWebSocket::disconnected, this, &WebServer::disconnected);
    connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(disconnected()));
    connect(socket, &QWebSocket::textFrameReceived, this, &WebServer::recvData);

    qDebug() << "connect";
    emit clientConnected();
}

void WebServer::start(const QString &ip, int port)
{
    listen(QHostAddress(ip), port);
}

void WebServer::disconnected()
{
     qDebug() << "diconnect";
     socket->deleteLater();
     emit clientDisconnected();
}

void WebServer::recvData(QString data)
{
    qDebug() << data;
    emit receiveData(data);
}

void WebServer::sendData(QString data)
{
    socket->sendTextMessage(data);
}





